package Service.Implement;

import Dao.Implement.roomDaoImplement;
import Dao.Implement.userDaoImplement;
import Dao.roomDao;
import Dao.userDao;
import Service.userService;
import com.sun.org.apache.bcel.internal.util.BCELifier;
import javafx.scene.input.DataFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import pojo.*;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;


@Service(value = "userServiceImplement")
public class userServiceImplement implements userService{
    @Autowired
    roomDao roomDao;
    @Autowired
    userDao userDao;

    @Override
    public int loginIn(String studentId, String password) {
        String pwd= userDao.loginIn(studentId).toString();
        if(pwd.equals(password)){
            return 1;
        }else{
            return 0;
        }
    }

    @Override
    public user queryUserByStudentId(String studentId) {
        return userDao.queryUserByStudentId(studentId);
    }

    @Override
    public int register(String studentID, String name, String pwd) {
        return userDao.register(studentID,name,pwd);
    }

    @Override
    public List<stadium> queryStadiumsByCategory(String sportID) {
        return userDao.queryStadiumBySportsId(sportID);
    }

    @Override
    public List<playground> queryPlaygroundByStadiumName(String stadiumName, String category) {
        Long stadiumId=userDao.queryStadiumByName(stadiumName).getStadium_id();
        return userDao.queryPlaygroundListByStadiumID(stadiumId,category);
    }


    @Override
    public String queryLeisureTime(String playgroundName, String stadiumName, String date) {

        Long stadiumId=userDao.queryStadiumByName(stadiumName).getStadium_id();

        //获取当前日期转为字符串，相等则表示查询今天 否则查询明天空闲时间
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date date1=new Date(System.currentTimeMillis());
        String date1String=simpleDateFormat.format(date1);
        String returnString=null;

        if(date1.equals(date)){
            returnString=userDao.queryPlaygroundByName(stadiumId,playgroundName).getBitmaps_today();
        }else{
            returnString=userDao.queryPlaygroundByName(stadiumId,playgroundName).getBitmaps_tomorrow();
        }

        return returnString;
    }

    @Override
    public int addUserMessage(Long userID, Long roomId, String content) {
        return userDao.sendMessage(userID,roomId,content);
    }

    @Override
    public List<message> queryMessageByRoomId(Long roomId) {
        return userDao.receiveMessage(roomId);
    }


    @Override
    public List<room> queryMatchingRoom() {
        return userDao.queryRoom();
    }

    /* 用于查询用户当前运动的pk值用于更新
                    @param sport_id 运动类别
                     1篮球 2网球 3足球 4乒乓球 5羽毛球 6排球 7棒球 8毽子
                    @return 用户当前的pk值
                     */
    private double querySportPK(double currentPK,String sport_id, Long user_id){
        double sportPk=0.0;
        user user=userDao.queryUserByID(user_id);
        switch (sport_id){
            case "1":
                sportPk=user.getPk_basketball();
                break;
            case "2":
                sportPk=user.getPk_tennis();
                break;
            case "3":
                sportPk=user.getPk_football();
                break;
            case "4":
                sportPk=user.getPk_pingpang();
                break;
            case  "5":
                sportPk=user.getPk_badminton();
                break;
            case "6":
                sportPk=user.getPk_volleyball();
                break;
            case "7":
                sportPk=user.getPk_baseball();
                break;
            case "8":
                sportPk=user.getShuttlecock();
                break;
            default:
                sportPk=currentPK;
        }
        return sportPk;
    }


    private int updateBitsmap(playground playground,int begintime ,int endtime,int timeflag){

         if(timeflag==1){
             //表示预约明天
             String timeMap=playground.getBitmaps_tomorrow();
             StringBuilder stringBuilder=new StringBuilder(timeMap);
             stringBuilder.replace(begintime,endtime,"0");
             playground.setBitmaps_tomorrow(stringBuilder.toString());

         }else{
             //表示预约今天
             String timeMap=playground.getBitmaps_today();
             StringBuilder stringBuilder=new StringBuilder(timeMap);
             stringBuilder.replace(begintime,endtime,"0");
             playground.setBitmaps_today(stringBuilder.toString());

         }
         return userDao.updatePlayground(playground.getPlayground_id(),playground.getBitmaps_today(),playground.getBitmaps_tomorrow());
    }






    @Override
    public List<room> queryMatchingRoomByCategory(String sports_id) {

        List<room> roomList=userDao.queryMatchingRoom(sports_id);

        roomList.sort(new Comparator<room>() {
            @Override
            public int compare(room o1, room o2) {
                return o1.getPk_match()>o2.getPk_match()?-1:0;
            }
        });


        return roomList;

    }


    @Override
    public List<user> LookOtherUser(Long room_id) {
      return userDao.queryUserIDByRoomID(room_id);
    }

    @Override
    public room queryRoomByRoomID(Long room_id) {
        return userDao.queryRoombyRoomID(room_id);
    }

    @Override
    public int joinRoom(Long user_id, String sport_id,Long room_id) {
        //借用三个标记位标记成功操作
        boolean operationOne=false,operationTwo=false,operationThree=false;
        room currentRoom= userDao.queryRoombyRoomID(room_id);
        int peopleNumber=currentRoom.getCurrent_number();
        double currentpk=currentRoom.getPk_match();
        //更新房间的人数
        int updateCurrentNumber=roomDao.updateCurrentNumber(peopleNumber+1,room_id);
        //设置标记位
        if(updateCurrentNumber!=-1){
            operationTwo=true;
        }
        double pkNeed=querySportPK(currentpk,sport_id,user_id);

        //更新当前房间的pk值
        int updatePK=roomDao.updateMatchValue((currentpk*peopleNumber+pkNeed)/(peopleNumber+1),room_id);

        if(updatePK!=-1){
            operationThree=true;
        }
        //将用户插入当前的房间列表
        int flagInsert=userDao.joinRoom(room_id,user_id,new java.sql.Date(currentRoom.getDate().getTime()),currentRoom.getSports_id());
        //设置标记位
        if(flagInsert!=-1){
            operationOne=true;
        }

        if(operationOne&&operationTwo&&operationThree){
            return 1;
        }
        return 0;

    }

    @Override
    public List<room> queryUserOrder(Long user_id) {
        return userDao.queryRoomOrderByUserID(user_id);
    }

    @Override
    public List<room> queryOrderByState(Long user_id, int roomstate) {
        return userDao.queryRoomOrderByRoomstate(user_id,roomstate);
    }

    @Override
    public Long createRoom(Long host_id, int capacity,String sport_id, String date, String stadium, String playgroundName, int begintime, int endtime) {
        room room=new room();
        //设置相关的参数
        room.setHost_id(host_id);
        room.setCapacity(capacity);
        room.setCurrent_number(1);
        room.setEnd_time(endtime);
        room.setSports_id(sport_id);
        room.setRoomstate(0);
        room.setPlayground(playgroundName);
        room.setStadium(stadium);
        room.setStart_time(begintime);

        //查询房主pk值

        double pkValue=querySportPK(0.0,sport_id,host_id);
        room.setPk_match(pkValue);
        //对于日期的处理
        Date date1=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        try {
            date1= simpleDateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        room.setDate(date1);

        //根据stadium查询价格

        Long stadium_id=userDao.queryStadiumByName(stadium).getStadium_id();

        playground playground=userDao.queryPlaygroundByName(stadium_id,playgroundName);
        float money=playground.getPrice();
        room.setMoney(money);
        //创建该房间
        int flagOne=userDao.createRoom(room);
        java.sql.Date date2=new java.sql.Date(date1.getTime());
        //查询到当前房间id 加入room_user表
        Long room_id=userDao.queryRoomID(host_id,date2,stadium,playgroundName).getRoom_id();
        int flagTwo=userDao.joinRoom(room_id,host_id,date2,sport_id);
        //更新bitmaps信息

        //获取当前时钟判断是更新今天还是明
        Date currentDate=new Date(System.currentTimeMillis());
        String currentDateString=simpleDateFormat.format(currentDate);
        int flagThree=0;
        if(currentDateString.equals(date)){
            //更新今天
           flagThree=updateBitsmap(playground,begintime,endtime,0);
        }else{
           flagThree=updateBitsmap(playground,begintime,endtime,1);
        }
        if((flagOne==1)&&(flagTwo==1)&&(flagThree==1)){
            return room_id;
        }

        return new Long("0");
    }

    @Override
    public user queryInformationByID(Long user_id) {
        return userDao.queryUserByID(user_id);
    }

    @Override
    public int deleteRoom(Long roomId) {
        int flagOne=userDao.deleteUserByRoomId(roomId);
        int flagTwo=userDao.deleteRoomById(roomId);

        if((flagOne!=-1)&&(flagTwo!=-1)){
            return 1;
        }
        return 0;
    }


    @Override
    public user queryUserByid(Long user_id) {
        return userDao.queryUserByID(user_id);
    }

    @Override
    public int exitRoom(Long roomId, Long userId) {
        int flagOne=userDao.exitRoom(roomId,userId);


        room currentRoom=roomDao.queryRoomById(roomId);
        int currentNumber=currentRoom.getCurrent_number();
        int flagTwo= roomDao.updateCurrentNumber( currentNumber-1,roomId);

        double currentpk=currentRoom.getPk_match();

        double pkNeed=querySportPK(currentpk,currentRoom.getSports_id(),userId);

        //更新当前房间的pk值
        int updatePK=roomDao.updateMatchValue((currentpk*currentNumber-pkNeed)/(currentNumber-1),roomId);

        if((flagOne==1)&&(flagTwo==1)&&(updatePK==1)){
            return 1;
        }
        return 0;
    }

    @Override
    public int updateRoomState(Long roomId, int roomstate) {
        return userDao.updateRoomState(roomId,roomstate);
    }

    @Override
    public int updatePhotoUrl(String studentID, String photoURL) {
        return userDao.updateUserPhoto(studentID,photoURL);
    }
}
